﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.OrmLite;
using ServiceStack.DataAnnotations;

namespace LCRReader
{
    public class GenneralConfig
    {
        [AutoIncrement, PrimaryKey]
        public int ID { get; set; }
        public string Section { get; set; }
        public string Key { get; set; }
        public string Value { get; set; }
    }
    public class GenneralConfigAccess
    {
        static string _path = "";
        static System.Data.IDbConnection _db = null;
        public static readonly GenneralConfigAccess Inst=new GenneralConfigAccess();
        private GenneralConfigAccess(string path = "./config/cfg.db")
        {
            if (path != _path)
            {
                _path = path;
                if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(path)))
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
                }
                OrmLiteConnectionFactory con = new OrmLiteConnectionFactory(path, SqliteDialect.Provider);

                _db = con.Open();
                if (!_db.TableExists<GenneralConfig>())
                {
                    _db.DropAndCreateTable<GenneralConfig>();

                }
            }
        }

        public long insert(string key, string value, string section = "Gennal")
        {
            return _db.Insert<GenneralConfig>(new GenneralConfig() { Key = key, Value = value, Section = section });
        }

        public string GetValue(string key, string section = "Gennal")
        {
            var list = _db.Where<GenneralConfig>(new { key = key, Section = section });
            if (list != null && list.Count > 0)
            {
                return list.First().Value;
            }
            else
                return "NA";
        }

        public int SetValue(string key, string value, string section = "Gennal")
        {
            if(GetValue(key,section)=="NA")
            {
                insert(key, value, section);
                return 0;
            }
            return _db.Update<GenneralConfig>(new { Key = key, Value = value, Section = section },p=>p.Key==key&&p.Section==section);
        }
    }
}
